import { HTMLAttributes, PropType, computed, defineComponent } from "vue";
import Tooltip from "../Tooltip";
import Avatar from "../Avatar";
import useChildren from "../use/useChildren";

export interface AvatarListProps extends HTMLAttributes {
    size?: 'small' | 'large',
    align?: 'top'|'bottom'|'left'|'right'|'topLeft'|'topRight'|'bottomLeft'|'bottomRight'|'leftTop'|'leftBottom'|'rightTop'|'rightBottom',
    gutter?: number,
    max?: number,
    excessStyle?: any,
}
export default defineComponent({
    name: 'AvatarList',
    props: {
        size: {
            type: String as PropType<AvatarListProps['size']>,
        },
        align: {
            type: String as PropType<AvatarListProps['align']>,
            default: 'top'
        },
        gutter: {
            type: Number as PropType<AvatarListProps['gutter']>,
        },
        max: {
            type: Number as PropType<AvatarListProps['max']>,
            default: Number.MAX_VALUE
        },
        excessStyle: {
            type: Object as PropType<AvatarListProps['excessStyle']>,
        }
    },
    setup (props, {slots}) {
        const classList = computed(() => ({
            'cm-avatar-list': true,
            [`cm-avatar-list-${props.size}`]: props.size
        }));

        const avatarsLength = computed(() => slots.default && slots.default().length);
        const gutter = computed(() => (props.gutter ?? (props.size === 'small' ? -8 : -12)) + 'px');

        const children = () => {
            const childs = useChildren({
                slots,
                props: {
                    size: props.size,
                },
                sameType: Avatar
            });
            if (childs) {
                const ret = [];
                childs.forEach((child, index: number) => {
                    if (index < props.max) {
                        ret.push(<div key={index} class="cm-avatar-list-item" style={{'margin-left': index > 0 ? gutter.value : 0}}>
                            <Tooltip align={props.align} content={child.props.title}>
                                {child}
                            </Tooltip>
                        </div>);
                    }
                });
                return ret;
            }
            return null;
        };

        return () => (
            <div class={classList.value}>
                {
                    children()
                }
                {
                    avatarsLength.value > props.max
                        ? <div class="cm-avatar-list-item">
                            <Avatar size={props.size} style={props.excessStyle}>+{avatarsLength.value - props.max}</Avatar>
                        </div>
                        : null
                }
            </div>
        );
    }
});

